package site.zhanjingbo.shop.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import site.zhanjingbo.shop.meta.Product;
import site.zhanjingbo.shop.meta.TRX;
import site.zhanjingbo.shop.meta.User;
import site.zhanjingbo.shop.service.ProductService;
import site.zhanjingbo.shop.service.TRXService;
import site.zhanjingbo.shop.utils.Permission;
import site.zhanjingbo.shop.utils.PermissionType;
import site.zhanjingbo.shop.utils.ResponseType;

@Controller
public class TRXController {

	@Resource
	private ProductService productService;

	@Resource
	private TRXService trxService;

	@Permission(permission = PermissionType.BUYER, response = ResponseType.JSON)
	@RequestMapping(value = "/api/buy", method = RequestMethod.POST)
	public Map<String, Object> buy(int id, HttpSession session, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<>();
		User user = (User) session.getAttribute("user");
		Product product = productService.getProductById(id);
		TRX trx = new TRX();
		trx.setUser(user);
		trx.setProduct(product);
		trx.setPrice(product.getPrice());
		trx.setTime(new Date().getTime());

		boolean flag = trxService.addTRX(trx);
		response.setStatus(300);
		if (flag) {
			result.put("message", "删除成功");
			response.setStatus(200);
		}
		result.put("code", response.getStatus());
		result.put("result", flag);
		return result;
	}

}
